package modulos.usuario.modelo;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author francisco
 */
public class Enlace {

    public static String getMac() {
        String s="";
        String so = System.getProperty("os.name");
        if (so.startsWith("Linux")) {
            s= sacarMacLinux();
        } else if (so.startsWith("Windows")) {
            s = sacarMacWindows();
        }
        return s;
    }

    private static String sacarMacLinux() {
        String mac = "";
        try {
            Process p = Runtime.getRuntime().exec("ifconfig");//ejecutar el comando ifconfig
            InputStream is = p.getInputStream();
            Scanner s = new Scanner(is);
            String m = s.nextLine();
            s.close();
            StringTokenizer st = new StringTokenizer(m);
            while (st.hasMoreTokens()) {
                mac = st.nextToken();
            }
        } catch (UnknownHostException ex) {
            Logger.getLogger(Enlace.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Enlace.class.getName()).log(Level.SEVERE, null, ex);
        }
        return mac;
    }

    private static String sacarMacWindows() {
        String s = "";
        try {
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface ni = NetworkInterface.getByInetAddress(ip);
            if (ni != null) {
                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {
                    
                    for (int i = 0; i < mac.length; i++) {
                        s += String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
                    }
                } else {
                    System.out.println("Direccion no existe o no es accessible.");
                }
            } else {
                System.out.println("Interfaz para la direccion especificada no existe");
            }
        } catch (UnknownHostException ex) {
            Logger.getLogger(Enlace.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SocketException ex) {
            Logger.getLogger(Enlace.class.getName()).log(Level.SEVERE, null, ex);
        }
        return s;
    }
  
}
